package frog

import (
	"fmt"
	"image/color"
	"math/rand"
	"sync"
	"time"

	"gitee.com/xntk2381/frog/egg"
	"github.com/hajimehoshi/ebiten/v2"
)

// 定义常量
const (
	SHOW_SPEED      = 1
	STEPS_PER_ROUND = 3000
	DELETE_EGGS     = true
)

// Env 表示青蛙的生存环境
type Env struct {
	ENV_XSIZE, ENV_YSIZE int
	Foods                [][]byte
	FOOD_QTY             int
	EGG_QTY              int
	Frogs                []*Frog
	Eggs                 []*egg.Egg
	Mu                   sync.Mutex // 用于并发安全
}

// NewEnv 创建一个新的环境
func NewEnv() *Env {
	env := &Env{
		ENV_XSIZE: 300,
		ENV_YSIZE: 300,
		FOOD_QTY:  2000,
		EGG_QTY:   80,
		Foods:     make([][]byte, 300),
		Frogs:     make([]*Frog, 0),
	}

	// 初始化食物数组
	for i := range env.Foods {
		env.Foods[i] = make([]byte, env.ENV_YSIZE)
	}

	// 如果需要删除蛋
	if DELETE_EGGS {
		fmt.Println("唵缚悉波罗摩尼莎诃!")
		DeleteEggs()
	}

	return env
}

// GetEggQty 返回蛋的数量
// func (e *Env) GetEggQty() int {
// 	return e.EGG_QTY
// }

// SetEggs 设置蛋列表
// func (e *Env) SetEggs(eggs []*egg.Egg) {
// 	e.Eggs = eggs
// }

// Run 运行环境
func (e *Env) Run() {
	// 从磁盘加载蛋，或新建一批蛋
	LoadEggs(e)

	// round:=1

	// 创建随机数生成器
	// r := rand.New(rand.NewSource(time.Now().UnixNano()))

	for {
		// 重建青蛙和食物
		e.rebuildFrogAndFood(r)

		// 模拟步骤
		allDead := false
		for i := 0; i < STEPS_PER_ROUND; i++ {
			if allDead {
				break
			}

			allDead = true
			e.Mu.Lock()
			for _, frog := range e.Frogs {
				if frog.Active(e) {
					allDead = false
				}
				if frog.Alive && frog.MoveCount == 0 && i > 100 {
					frog.Alive = false
				}
			}
			e.Mu.Unlock()

			// 控制模拟速度
			time.Sleep(10 * time.Millisecond)
		}

		LayEggs(e)

		// 短暂休眠
		// time.Sleep(100 * time.Millisecond)
	}
}

// rebuildFrogAndFood 重建青蛙和食物
func (e *Env) rebuildFrogAndFood(r *rand.Rand) {
	e.Mu.Lock()
	defer e.Mu.Unlock()

	// 清空青蛙列表
	e.Frogs = e.Frogs[:0]

	// 清空食物
	for i := 0; i < e.ENV_XSIZE; i++ {
		for j := 0; j < e.ENV_YSIZE; j++ {
			e.Foods[i][j] = 0
		}
	}

	// 从蛋生成青蛙
	for _, egg := range e.Eggs {
		for j := 0; j < 4; j++ {
			x := e.ENV_XSIZE/2 + r.Intn(90)
			y := e.ENV_YSIZE/2 + r.Intn(90)
			frog, err := NewFrog(x, y, egg)
			if err == nil {
				e.Frogs = append(e.Frogs, frog)
			}
		}
	}

	fmt.Printf("Created %d frogs\n", len(e.Frogs))

	// 随机生成食物
	for i := 0; i < e.FOOD_QTY; i++ {
		x := r.Intn(e.ENV_XSIZE - 3)
		y := r.Intn(e.ENV_YSIZE - 3)
		e.Foods[x][y] = 1
	}
}

// DrawFood 绘制食物
func (e *Env) DrawFood(screen *ebiten.Image) {
	black := color.RGBA{0, 0, 0, 255}

	e.Mu.Lock()
	defer e.Mu.Unlock()

	for x := 0; x < e.ENV_XSIZE; x++ {
		for y := 0; y < e.ENV_YSIZE; y++ {
			if e.Foods[x][y] > 0 {
				// 绘制4x4的食物
				for dx := 0; dx < 4; dx++ {
					for dy := 0; dy < 4; dy++ {
						// 确保不超出屏幕边界
						if x+dx < e.ENV_XSIZE && y+dy < e.ENV_YSIZE {
							screen.Set(x+dx, y+dy, black)
						}
					}
				}
			}
		}
	}
}
